// 默认配置
neutron.setTitle("Editor")
neutron.setMinSize(500, 350)
neutron.getInfo((data) => {
    if (data[0]["w"] < 500) {
        neutron.setWinSize(600, 400)
    }
});


// 配置
var language = "text"
var filepath = ""
var filetext = ""
var readonly = false
var save = false
var encoding = "utf-8"

window.onload = function () {
    // 从会话换源
    neutron.loadData((loadobjs) => {
        var loadobj = loadobjs[0]
        if (location.hash != "" && location.hash != "#") {
            filepath = location.hash.split("#")[1]
            location.hash = ""
            setTimeout(() => {
                open_file()
            }, 1000)
        }
        if (loadobj != null) {
            // 存在会话
            language = loadobj.language;
            filepath = loadobj.filepath;
            filetext = loadobj.text;
            readonly = loadobj.readonly;
            save = loadobj.save;
            encoding = loadobj.encoding;
            neutron.setTitle("Editor - " + filepath)
        }
        require(['vs/editor/editor.main'], function () {
            // 创建编辑器
            window.editor = monaco.editor.create(document.getElementById("container"), {
                value: filetext,
                language: language,
                fixedOverflowWidgets: true,
                fontFamily: "Editor Fonts",
                fontSize: 14,
                tabSize: 4,
                insertSpaces: true,
                readOnly: readonly,
                wordWrap: 'on',
                automaticLayout: true,
                scrollBeyondLastLine: false,
                cursorSmoothCaretAnimation: false,
                folding: true,
                scrollbar: {
                    verticalScrollbarSize: 8,
                    horizontalScrollbarSize: 8,
                },
            });
            setInterval(() => {
                neutron.saveData(
                    {
                        "text": window.editor.getModel().getValue(),
                        "language": language,
                        "filepath": filepath,
                        "readonly": readonly,
                        "save": save,
                        "encoding": encoding
                    }
                ) // 定时保存会话
            }, 5000);
            document.getElementById("header").style.visibility = "visible" // 显示菜单栏

            // 保存到window对象
            window.monaco = monaco

            // 绑定快捷键
            window.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, function () {
                save_file()
            })
        });
    });
}

function open_file() {
    console.log("Open file")
    if (filepath != "") { // 未打开文件则忽略
        console.log("Open file: " + filepath)
        var xhr = new XMLHttpRequest();
        xhr.open("GET", API_PATH + "/file?filepath=" + filepath + "&encoding=" + encoding, true);
        xhr.onload = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = JSON.parse(xhr.responseText);
                // 设置参数
                filetext = data.filetext;
                readonly = data.readonly
                save = data.save
                filepath = data.filepath
                language = data.language

                // 设置编辑器
                setTimeout(() => {
                    window.editor.getModel().setValue(filetext)
                    window.monaco.editor.setModelLanguage(window.editor.getModel(), language);
                    window.editor.updateOptions({
                        value: filetext,
                        language: language,
                        readOnly: readonly
                    });
                    neutron.setTitle("Editor - " + filepath)
                }, 20)
            }
        }
        xhr.send();
    }
}
function open_file_window() {
    // 打开文件对话框
    neutron.createIframeWin("Open", "/api/plugin/filemanager/iframe/index.html?" + (new URLSearchParams({
        "choose": "file",
        "choose_callback": neutron.winid,
        "choose_callback_id": "open"
    }).toString()
    ), 0, 0)
}
function save_file() {
    console.log("Save file")
    if (save == true && filepath != "") { // 允许保存
        var xhr = new XMLHttpRequest();
        xhr.open("POST", API_PATH + "/file?filepath=" + filepath + "&encoding=" + encoding, true);
        xhr.onload = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = JSON.parse(xhr.responseText);
                neutron.setTitle("Editor - " + filepath)
                if (data.code != 0) {
                    alert(data.message)
                }
            }
        }
        const formData = new FormData();
        formData.append("text", window.editor.getModel().getValue());
        xhr.send(formData);
    }
}
function save_as_file() {
    // 保存文件对话框
    neutron.createIframeWin("Save", "/api/plugin/filemanager/iframe/index.html?" + (new URLSearchParams({
        "choose": "file",
        "choose_callback": neutron.winid,
        "choose_callback_id": "save"
    }).toString()
    ), 0, 0)
}
function set_encoding() {
    // 更改编码对话框
    neutron.showContextMenu((data) => {
        var ret = data[0]
        if (ret == 2) {
            return
        }
        neutron.showContextMenu((data) => {
            var ret2 = data[0]
            var coding = ["utf-8", "gbk", "utf-16", "utf-32", "cp950"][ret2]
            encoding = coding
            if (ret == 0) {
                save_file()
            } else {
                reload_file()
            }
        }, ["UTF-8", "GBK", "UTF-16", "UTF-32", "Big5"], 136, 24)
    }, ["以编码保存", "以编码读取"], 136, 24)
}
function reload_file() {
    // 重载
    open_file()
}

window.addEventListener("message", winapi_receiveMessage, false); // 接收选择文件回调
function winapi_receiveMessage(event) {
    if (event.origin != location.origin) {
        return;
    }
    var data = event.data;
    if (data["type"] != "choose_file") {
        return
    }
    if (data["id"] == "open") {
        filepath = data["data"]
        open_file()
    } else if (data["id"] == "save") {
        filepath = data["data"]
        save_file()
    }
}

